from scipy.io.wavfile import write
import numpy as np
from scipy.io import wavfile

# 读取音频文件
samplerate, data = wavfile.read('C:/Users/JSJSYS/gitcode/student_repo_026/labs/lab06/wavefile/10s_2.wav')

# 确保数据是浮点数格式以便处理
data_float = data.astype(np.float64)

# 归一化到[-1, 1]范围
if data_float.max() > 1.0 or data_float.min() < -1.0:
    max_abs = max(abs(data_float.max()), abs(data_float.min()))
    data_float = data_float / max_abs

# 缩放到int16范围
amplitude = np.iinfo(np.int16).max
data_scaled = (data_float * amplitude).astype(np.int16)

# 保存完整的重新缩放的音频
write("example.wav", samplerate, data_scaled)

# 分割为1秒片段
if samplerate == 44100:
    samples_per_second = 44100
else:
    samples_per_second = samplerate  # 如果不是44100，使用实际采样率

# 计算总秒数
total_seconds = len(data) // samplerate

# 分割并保存每个1秒片段
for i in range(total_seconds):
    start = i * samples_per_second
    end = start + samples_per_second
    
    # 确保不越界
    if end <= len(data_scaled):
        segment = data_scaled[start:end]
        
        # 保存片段
        output_filename = f"segment_{i+1}.wav"
        write(output_filename, samplerate, segment)
        print(f"已保存: {output_filename}")
    else:
        # 处理最后不足1秒的部分
        segment = data_scaled[start:]
        output_filename = f"segment_{i+1}_remaining.wav"
        write(output_filename, samplerate, segment)
        print(f"已保存剩余部分: {output_filename}")
        break

print(f"分割完成，共生成 {min(total_seconds, len(data)//samples_per_second)} 个片段")